from flask import Flask, render_template, Response,jsonify,request
import tr
import config
import json
import os.path
import requests
import numpy as np


url = 'http://10.9.102.133:8061'

app = Flask(__name__)
app.config.from_object(config)
class NpEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        else:
            return super(NpEncoder, self).default(obj)
class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        if isinstance(obj, time):
            return obj.__str__()
        else:
            return super(NpEncoder, self).default(obj)
def listToJson(lst):
    import json
    import numpy as np
    keys = [str(x) for x in np.arange(len(lst))]
    list_json = dict(zip(keys, lst))
    str_json = json.dumps(list_json, indent=2, ensure_ascii=False,cls=NpEncoder)  # json转为string
    return  str_json

@app.route('/')
def index():
    return render_template('index.html')



@app.route('/upload/', methods=['POST'])
def uploadiamge():
    '''
    save a pic on py project from local pc
    :return:
    '''
    file = request.files['filechoose']
    print(request.args['fname'])
    file.save("image/"+request.args['fname'])
    print("uploadImage ---------------"+request.args["fname"])
    #cmd = "python3 "">image/"+request.args['fname']+".json"
    #os.system("")
    print("image/"+request.args['fname'])
    ret = tr.run("image/"+request.args['fname'])
    ret_str = json.dumps(ret,cls=MyEncoder)
    #ret_json = listToJson(ret)
    return ret_str

def use_detect_api():
    module_path = os.path.dirname(__file__)
    f = open(module_path + '/image/test.jpg', 'rb')#如果不加b，则会报转码错误
    file = {'image': f}

    #r 是个response对象
    r = requests.post(url + '/detect', files=file)
    #print(type(r.text)) #str
    resJson = json.loads(r.text)
    #print(type(resJson)) #dict
    #1.会将内容转换为json，
    #2.修改Content-Type为application/json。
    return jsonify(resJson)
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8090)